package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SmallVideosService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发布视频
     * @param videoThumbnail ：封面图片
     * @param videoFile ： 视频文件
     */
    //@CacheEvict(value = "videos",allEntries = true)
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //视频上传到FastDFS
        String filename = videoFile.getOriginalFilename(); 
        filename = filename.substring(filename.lastIndexOf(".")+1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(),
                videoFile.getSize(), filename, null);//文件输入流，文件长度，后缀名，元数据
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //图片上传到阿里云OSS上
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //构造视频对象，调用API保存
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setVideoUrl(videoUrl);
        video.setPicUrl(imageUrl);
        video.setCreated(System.currentTimeMillis());
        video.setText("我就是我，不一样的烟火");
        videoApi.save(video);
    }

    public static void main(String[] args) {
        String name = "123.123435.avi";
        String s = name.substring(name.lastIndexOf(".") + 1);
        System.out.println(s);
    }

    /**
     * 分页查询视频列表
     *  1、存入redis中
     *  2、当redis不存在，调用service方法，完成查询
     *  3、写入redis中
     *    key : videos:: userId_page_size
     *
     *        videos：106_1_10
     *                106_2_10
     *                106_3_10
     *        videos：1_1_10
     *                1_2_10
     *                1_3_10
     *    发动态
     */
    //@Cacheable(value = "videos",key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page + '_' + #pagesize")
    public PageResult findVideos(Integer page, Integer pagesize) {
        System.out.println("调用service方法查询视频列表");
        Long userId = UserHolder.getUserId();
        //1、查询redis中的数据
        String key = Constants.VIDEOS_RECOMMEND + userId;
        String value = redisTemplate.opsForValue().get(key);
        //2、redis数据不存在，调用API从Mongdb中查询
        List<Video> list = new ArrayList<>();
        if(StringUtils.isEmpty(value)) {
            //调用API查询所有
            list = videoApi.findAll(page,pagesize);
        }else {
            //调用API，根据id查询
            String[] ids = value.split(",");
            list = videoApi.findByIds(ids,page,pagesize);
        }
        if(list==null || list.size()<=0) {
            return new PageResult();
        }
        //3、将Video对象转化为vo
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo userInfo = map.get(video.getUserId());
            VideoVo vo = VideoVo.init(userInfo, video);
            vos.add(vo);
        }
        return new PageResult(page,pagesize,0l,vos);
    }
}
